<template>
	<view class="page-container">
		<!-- 轮播图部分 -->
		<view class="container-pic">
			<swiper class="pic-swiper" circular :autoplay="false" :interval="1000" indicator-dots="true" :duration="500"
				indicator-color="rgba(255,255,255,0.5)" indicator-active-color="white">
				<swiper-item v-for="(item,index) in imgList" :key="index">
					<image :src="item" style="width:100%;height: 720rpx;"></image>
				</swiper-item>
			</swiper>
		</view>
		<!-- 主题部分 -->
		<view class="container-title">
			<text>{{title}}</text>
			<view class="price">
				<text class="red-color"
					v-if="activity">￥{{activity.groupShopSkuDTOList[0].skuGroupShopPrice*0.01}}</text>
				<text v-else
					class="red-color">￥{{level==1?choosedProduct.vipPrice*0.01:choosedProduct.price*0.01}}</text>
				<text class="origin-price">￥{{choosedProduct.originalPrice*0.01}}</text>
				<uni-tag v-if="activity" text="团购" customStyle="background-color: #FA436A;border:0;" />
				<uni-tag v-else :text="level==1?'VIP':((price*10/originalPrice).toFixed(1)).toString()+'折'" size="small"
					customStyle="background-color: #FA436A;border:0;"></uni-tag>
			</view>
			<view class="sale-stock">
				<view>销量:{{sales}}</view>
				<view>库存:{{Object.values(this.choosedSku).length?choosedProduct.stock:stock}}</view>
			</view>
		</view>
		<!-- 团购信息部分 -->
		<view class="container-group" v-if="activity">
			<view class="group-icon">
				<view class="icon-star">
					<u-icon name="star-fill" color="white"></u-icon>
				</view>
				<view class="icon-font">团</view>
			</view>
			<view v-if="activity">{{activity.minNum}}人成团，已有{{activity.buyerNum}}人参团</view>
			<view class="group-tell">
				<u-icon name="question-circle"></u-icon>
				<text style="color: #FA436A;margin-left: 10rpx;">告诉TA</text>
				<u-icon name="arrow-right" color="#FA436A"></u-icon>
			</view>
		</view>
		<!-- 基本信息部分 -->
		<view class="container-sheet">
			<u-cell isLink @click="openSpuWindow">
				<text slot="title" style="font-size: 30rpx;">购买类型</text>
				<text slot="value" class="sheet-value"
					style="margin-right: 0rpx;">{{Object.values(this.choosedSku).length?Object.values(this.choosedSku).join(","):'请选择'}}</text>
			</u-cell>
			<u-cell isLink center @click="openCouponWindow ">
				<text slot="title" style="font-size: 30rpx;">优惠券</text>
				<text slot="value" class="sheet-value" style="color: #FA436A;margin-right: 0rpx;">领取优惠券</text>
			</u-cell>
			<u-cell>
				<text slot="title" style="font-size: 30rpx;">配送费用</text>
				<text slot="value"
					class="sheet-value">{{freightTemplate&&freightTemplate.defaultFreePrice?`单笔购买满￥${freightTemplate&&freightTemplate.defaultFreePrice/100}元免邮费`:'包邮'}}</text>
			</u-cell>
			<u-cell center v-for="item in attributeList" :key="item.id">
				<text slot="title" style="font-size: 30rpx;">{{item.attribute}}</text>
				<text slot="value" class="sheet-value">{{item.value}}</text>
			</u-cell>
		</view>
		<view class="isolation" style="margin-top: 0;"></view>
		<!-- 图文详情部分 -->
		<view class="container-pictext">
			<view style="width: 50%;margin: auto;">
				<u-divider text="图文详情" textSize="30rpx" textColor="black" lineColor="D2D2D2"></u-divider>
			</view>
			<view class="u-content">
				<u-parse :content="detail" :tagStyle="{img:'vertical-align:bottom ;width:100%;'}"></u-parse>
			</view>
		</view>
		<view style="height: 50rpx;width: 100%;"></view>
		<!-- 商品导航 -->
		<view class="container-goodsNav">
			<uni-goods-nav :fill="true" :options="options" :button-group="buttonGroup" @click="onClick"
				@buttonClick="buttonClick" />
		</view>
		<!-- 购买类型弹出框 -->
		<view class="">
			<u-popup :show="show" mode="bottom" @close="close" @open="open"
				:customStyle="{borderRadius: '10rpx 10rpx 0 0'}">
				<view class="popup-box">
					<view class="popup-title">
						<image :src="choosedProduct.img" style="width: 200rpx;height: 200rpx;"></image>
						<view class="title-text">
							<text
								class="red-color">￥{{choosedProduct.groupSku?choosedProduct.groupSku.skuGroupShopPrice*0.01:choosedProduct.price*0.01}}</text>
							<view style="margin: 10rpx 0;">
								<text>库存：</text><text>{{choosedProduct.stock}}件</text>
							</view>
							<view>
								<text>已选：</text><text>{{choosedProduct.title}}</text>
							</view>
						</view>
					</view>
					<view style="height: 200rpx;"></view>
					<view class="attr-num">
						<view class="popup-attr" v-for="item in specificationComputed" :key="item.id">
							<view style="margin: 10rpx 0;">{{item.title}}</view>
							<view class="attr-content">
								<u-tag :text="data" v-for="data in item.sku" :key="data" shape="circle" plainFill plain
									borderColor="transparent" :type="choosedSku[item.title] === data?'error':'info'"
									@click="handleChangeProduct(item.title,data)"></u-tag>
							</view>
						</view>
						<view class="popup-num">
							<view style="margin: 20rpx 0;">数量</view>
							<view style="padding-left: 20rpx;">
								<u-number-box v-model="popupNum" :min="1"></u-number-box>
							</view>
						</view>
						<view style="padding: 30rpx;">
							<u-button type="error" shape="circle" @click="handleFinish">完成</u-button>
						</view>
					</view>

				</view>
			</u-popup>
		</view>
		<!-- 优惠券弹出框 -->
		<view class="">
			<u-popup :show="couponShow" :round="10" mode="bottom" @close="couponClose" @open="couponOpen">
				<view class="coupon-box">
					<view class="coupon-item" v-for="item in couponList" :key="item.id">
						<view class="item-detail">
							<view>
								<view style="font-size: 35rpx;text-align: left;">{{item.title}}</view>
								<view>
									<text
										style="color: gray;">在领取后的{{item.days}}内有效。可领取{{item.limit}},已领取{{item.nowCount}}</text>
								</view>
							</view>
							<view>
								<view style="color: #FA436A;font-size: 35rpx;">￥{{item.discount*0.01}}</view>
								<view>满{{item.min*0.01}}可用</view>
							</view>
						</view>
						<view class="item-type">
							<view>{{item.type === 1?'指定类目可用':'全场商品可用'}}</view>
							<view class="type-icon" style="">
								已领取
							</view>
						</view>
					</view>
				</view>
			</u-popup>
		</view>
	</view>
</template>

<script>
	import {
		get
	} from '../../utils/http'
	import {$skuList} from '@/globaldata/index.js'
	import {checkAuth} from '../../utils/checkAuth.js'
	export default {
		data() {
			return {
				//是否会员，0普通用户  1vip用户
				level: 0,
				//轮播图片
				imgList: [],
				//主题
				title: '',
				//价格处理
				originalPrice: 0,
				price: 0,
				vipPrice: 0,
				//商品图片
				img:'',
				//商品id
				id:0,
				//类目id
				categoryId:0,
				//类目层级id
				categoryIdList:[],
				//销量
				sales: 0,
				//库存
				stock: 0,
				//团购活动
				activity: null,
				//规格属性
				attributeList: [],
				//运费
				freightTemplate: null,
				//图文详情
				detail: '',
				//sku列表
				skuList: [],
				//specificationList
				specificationList: [],
				//购买类型弹出框
				show: false,
				//商品详情中的数量
				popupNum: 1,
				//选择好的商品数据
				choosedSku: {},
				//优惠券弹出框
				couponShow: false,
				//可领取优惠券列表
				couponList: [],
				finishRun:null,
				options: [{
					icon: 'home-filled',
					text: '首页'
				}, {
					icon: 'cart',
					text: '购物车',
				}, {
					icon: 'heart', //heart-filled
					text: '收藏',
				}],
				buttonGroup: [{
						text: '立即参团',
						backgroundColor: 'linear-gradient(to right,#ffac30,#fa436a)',
						color: '#fff'
					},
					{
						text: '加入购物车',
						backgroundColor: 'linear-gradient(to right,#fa436a,#f56c6c)',
						color: '#fff'
					}
				]
			}
		},
		onLoad(options) {
			const id = options.id
			this.level = JSON.parse(uni.getStorageSync('user') || '{}').level
			get("product", "getProduct", {
				spuId: id
			}).then(res => {
				console.log(res)
				const {
					data,
					errmsg,
					errno
				} = res
				if (200 == errno) {
					this.imgList = data.imgList
					this.title = data.title
					this.img = data.img
					this.id = data.id
					this.categoryId = data.categoryId
					this.categoryIdList = data.categoryIds
					this.originalPrice = data.originalPrice
					this.price = data.price
					this.vipPrice = data.vipPrice
					this.sales = data.sales
					// this.stock = data.skuList[0].stock
					this.attributeList = data.attributeList
					data.skuList.forEach(item => {
						this.stock += item.stock
					})
					this.activity = data.activity
					this.freightTemplate = data.freightTemplate || {}
					this.detail = data.detail
					this.skuList = data.skuList
					this.specificationList = data.specificationList
				} else {
					uni.showToast({
						icon: 'none',
						title: errmsg
					})
				}
			})
		},
		methods: {
			onClick(e) {
				uni.showToast({
					title: `点击${e.content.text}`,
					icon: 'none'
				})
			},
			buttonClick(e) {
				console.log(111,e)
				this.createOreder()
				// this.options[2].info++
			},
			/**
			 * 打开购买类型对话框之前设置默认的值
			 */
			open() {
				let that = this
				let keys = Object.keys(that.choosedSku)
				if (0 === keys.length) {
					let skuKeys = that.specificationList.map(item => item.title)
					skuKeys.forEach((item, index) => {
						that.$set(that.choosedSku, item, that.specificationList[index].sku[0])
					})
				}
			},
			close() {
				this.show = false
				// console.log('close');
			},
			couponClose() {
				this.couponShow = false
			},
			couponOpen() {
				console.log('open');
			},
			/**
			 * 打开购买类型对话框
			 */
			openSpuWindow() {
				this.show = true
			},
			handleChangeProduct(classes, attr) {
				this.choosedSku[classes] = attr
			},
			/**
			 * 打开优惠券对话框
			 */
			openCouponWindow() {
				if(checkAuth()){
					let user = JSON.parse(uni.getStorageSync('user') || '{}')
					get('coupon', 'getObtainableCoupon', user.id).then(res => {
						console.log(res)
						const {
							data,
							errmsg,
							errno
						} = res
						if (200 == errno) {
							this.couponList = data
						} else {
							uni.showToast({
								title: errmsg,
								icon: 'error'
							})
						}
					})
					this.couponShow = true
				}
			},
			/**
			 * 构建订单数据
			 */
			createOreder(){
				if(this.hasChooseSku){
					let pro = this.choosedProduct
					console.log(this.popupNum)
					let skuItem = {
						skuId:pro.id,//规格id
						num:this.popupNum,//购买数量
						title:this.title,//商品标题
						freightTemplateId:this.freightTemplate.id,//运费模板id
						originalPrice:pro.originalPrice,//原价
						price:pro.groupSku&&pro.groupSku.skuGroupShopPrice||(this.level?pro.vipPrice:pro.price),//现价
						vipPrice:pro.vipPrice,//vip价
						skuTitle:pro.title,//规格标题
						spuImg:this.img,//商品图片
						skuImg:pro.img, //规格图片
						stock:pro.stock,//所选规格库存
						spuId:this.id,//商品id
						categoryId:this.categoryId,//类目id
						categoryIdList:this.categoryIdList,//类目层级id
						weight:pro.weight//商品重量
					}
					if(this.activity){
						skuItem['groupShopId'] = pro.groupSku.id
					}
					// $skuList.length = 0
					$skuList.push(skuItem)
					uni.navigateTo({
						url:'/pages/order/create?takeway=buy'
					})
				}else{
					this.show = true
					this.finishRun = this.createOreder
				}
			},
			/**
			 * 购买类型弹出框点击完成
			 */
			handleFinish(){
				this.show = false
				let finish = this.finishRun || null
				if(finish){
					this.finishRun()
					this.finishRun = null
				}
			}
			

		},
		computed: {
			specificationComputed() {
				let newArr = this.skuList.map(item => item.title).map(item => item.split(","))
				this.specificationList.forEach((item, index) => {
					let tempArr = []
					newArr.forEach((data) => {
						if (tempArr.includes(data[index])) return
						tempArr.push(data[index])
					})
					item.sku = tempArr
				})
				return this.specificationList
			},
			choosedProduct() {
				let that = this
				let skuList = that.skuList || []
				let choosedSku = that.choosedSku
				let skuKeys = Object.keys(choosedSku)
				//当没有选中时，默认加载的数据
				if (skuKeys.length == 0) {
					const {
						price,
						vipPrice,
						originalPrice
					} = that
					let groupSku = that.activity?.groupShopSkuDTOList[0]
					return {
						price,
						vipPrice,
						originalPrice,
						groupSku
					}
				}
				//将选中的choosedSku的key和value拼接
				let specification = skuKeys.map(key => choosedSku[key]).join()
				let product = skuList.find(item => item.title == specification)
				//团购处理
				if (that.activity && product) {
					let skuId = product.id
					let groupSkuList = that.activity.groupShopSkuDTOList || []
					let groupSku = groupSkuList.find(item => item.skuId === skuId) || {}
					product.groupSku = groupSku
				}
				console.log(product)
				return product || {}
			},
			/**
			 * 是否选择规格
			 */
			hasChooseSku(){
				let that = this 
				let chooseSku = that.choosedSku || {}
				let skuKeys = Object.keys(chooseSku)
				return skuKeys.length > 0
			}
		}
	}
</script>

<style lang="scss" scoped>
	.page-container {
		.pic-swiper {
			height: 720rpx;
		}

		.container-title {
			font-size: 35rpx;
			padding: 20rpx 30rpx;

			.price {
				display: flex;
				align-items: center;
				padding: 20rpx 0;

				.origin-price {
					color: gray;
					text-decoration: line-through;
					font-size: 25rpx;
					margin: 0 20rpx;
				}
			}

			.sale-stock {
				font-size: 20rpx;
				display: flex;
				justify-content: space-between;

				>view {
					width: 250rpx;
				}
			}
		}

		.container-group {
			background-color: #f5f5f5;
			padding: 20rpx 30rpx;
			display: flex;
			justify-content: space-between;
			align-items: center;
			font-size: 30rpx;

			.group-icon {
				display: flex;
				width: 80rpx;
				border: 1rpx solid $red;

				>view {
					flex: 1;
				}

				.icon-star {
					background-color: $red;
					display: flex;
					align-items: center;
					justify-content: center;
					border-radius: 0 20rpx 20rpx 0;
				}

				.icon-font {
					color: $red;
					text-align: center;
				}
			}

			.group-tell {
				display: flex;

			}
		}

		.container-sheet {
			.sheet-value {
				font-size: 30rpx;
				flex: 2.5;
				margin-right: 40rpx;
			}
		}

		.container-goodsNav {
			width: 94%;
			position: fixed;
			bottom: 30rpx;
			left: 50%;
			transform: translateX(-50%);
			border-radius: 16rpx;
			box-shadow: 0 0 10px 0 rgba(0, 0, 0, 0.5);
		}
	}

	.red-color {
		color: $red;
	}

	/deep/.uni-tab__cart-box {
		border-radius: 16rpx;
	}

	.popup-box {
		position: relative;

		// height: 400rpx;
		.popup-title {
			display: flex;
			font-size: 30rpx;
			position: absolute;
			height: 180rpx;
			left: 0;
			top: 0;

			image {
				// position: absolute;
				margin-left: 20rpx;
				margin-top: -20rpx;
				margin-right: 10rpx;
				border-radius: 10rpx;
			}
		}

		.popup-attr {
			padding: 0 30rpx;

			.attr-content {
				display: flex;
				flex-wrap: wrap;

				/deep/.u-tag-wrapper {
					margin-left: 20rpx;
					margin-top: 20rpx;
				}
			}
		}

		.attr-num {
			height: 600rpx;
			overflow: scroll;
		}

		.popup-num {
			padding: 0 30rpx;
		}
	}

	.coupon-box {
		background-color: #f5f5f5;
		padding: 30rpx;
		border-radius: 10rpx 10rpx 0 0;
		height: 800rpx;
		overflow-y: scroll;

		.coupon-item {
			margin-top: 10rpx;
			font-size: 25rpx;
			text-align: center;

			.item-detail {
				background-color: white;
				display: flex;
				justify-content: space-between;
				padding: 20rpx;
			}

			.item-type {
				position: relative;
				background: white;
				margin-top: 4rpx;
				padding: 20rpx;
				text-align: left;

				.type-icon {
					border: 1rpx solid;
					height: 80rpx;
					width: 80rpx;
					border-radius: 50%;
					text-align: center;
					line-height: 80rpx;
					position: absolute;
					right: 40rpx;
					top: -20rpx;
					transform: rotate(-40deg);
				}

				&::before {
					width: 30rpx;
					height: 30rpx;
					background-color: #f5f5f5;
					border-radius: 50%;
					content: '';
					display: inline-block;
					position: absolute;
					top: -15rpx;
					left: -15rpx;
				}

				&::after {
					width: 30rpx;
					height: 30rpx;
					background-color: #f5f5f5;
					border-radius: 50%;
					content: '';
					display: inline-block;
					position: absolute;
					top: -15rpx;
					right: -15rpx;
				}
			}
		}
	}
</style>
